<?php
namespace app\admin\model;

use think\Model;

class TpCategory extends Model
{
	protected $field=true;
	protected static function init()
	{

        TpCategory::beforeUpdate(function ($category) {
            $categoryId=$category->id; 
            $categoryData=input('post.');
            // dump($categoryData);die;
            $categoryData=input('post.');
            foreach ($categoryData['attr_id'] as $k => $v) {
                if(empty($v)){
                    unset($categoryData['attr_id'][$k]);
                }
            }
            if($categoryData['attr_id']){
                 $categoryData['attr_id']=implode(',',$categoryData['attr_id']);
            $category->search_attr_ids= $categoryData['attr_id'];
            }

            //处理商品推荐位
            if(isset($categoryData['recpos'])){
                db('tp_rec_item')->where(['value_id'=>$categoryId,'value_type'=>2])->delete();
                foreach ($categoryData['recpos'] as $k => $v) {
                    db('tp_rec_item')->insert(['recpos_id'=>$v,'value_id'=>$categoryId,'value_type'=>2]);
                }
            }

        });






        TpCategory::afterInsert(function($category){
            $categoryId=$category->id; 
            $categoryData=input('post.');

            //处理商品推荐位
            if(isset($categoryData['recpos'])){
                foreach ($categoryData['recpos'] as $k => $v) {
                    db('tp_rec_item')->insert(['recpos_id'=>$v,'value_id'=>$categoryId,'value_type'=>2]);
                }

            }

        });



        TpCategory::beforeInsert(function ($category) {
       
            $categoryData=input('post.');
            foreach ($categoryData['attr_id'] as $k => $v) {
                if(empty($v)){
                    unset($categoryData['attr_id'][$k]);
                }
            }
            if($categoryData['attr_id']){
                 $categoryData['attr_id']=implode(',',$categoryData['attr_id']);
            $category->search_attr_ids= $categoryData['attr_id'];
            }
           

        });


        



}
}